package org.example.netty.test.nio.netty.chat.util;

import org.example.netty.test.nio.netty.chat.bean.User;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zp
 * @version 1.0
 * @description: 文件工具类 读取文件资源
 * @date 2023/5/20 14:44
 */
public class FileUtil {
    public static final String USER_FILE_NAME = "RegisterUserFile.txt";
    /**
     * @param fileName
     * @return String
     * @description: 获取类路径下面文件
     * @author zp
     * @date: 2023/5/20 14:47
     */
    public static String getClassPathFileUrl(String fileName) {
        ClassLoader classLoader = FileUtil.class.getClassLoader();
        //getResource()方法会去classpath下找这个文件，获取到url resource,
        //得到这个资源后，调用url.getFile获取到 文件 的绝对路径
        URL url = classLoader.getResource(fileName);
        //url.getFile() 得到这个文件的绝对路径
        assert url != null;
        return url.getPath();
    }

    /**
     * @description:  读取用户注册文件 持久化
     * @author zp
     * @date: 2023/5/20 15:01
     * @return List<User>
     */
    public static List<User> readUserList() throws Exception{
        Path path = createFile(USER_FILE_NAME);
        BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
        List<User> userList = new ArrayList<>();
        while (reader.ready()) {
            String userName = reader.readLine();
            String password = reader.readLine();
            User user = new User();
            user.setUserName(userName);
            user.setPassword(password);
            userList.add(user);
        }
        reader.close();
        return userList;
    }

    /**
     * @description:  写入注册成功的用户信息
     * @author zp
     * @date: 2023/5/20 15:06
     * @param userName
     * @param password
     */
    public static void writeUserList(String userName,String password) throws Exception{
        Path path = createFile(USER_FILE_NAME);
        BufferedWriter write = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
        write.append(userName).append("\n");
        write.append(password).append("\n");
        write.flush();
        write.close();
    }

    /**
     * @description:  创建文件 返回路径对象
     * @author zp
     * @date: 2023/5/20 15:03
     * @return Path
     */
    public static Path createFile(String fileName) throws IOException {
        // win 路径有问题 需要截断第一个字符
        String classPathFileUrl = getClassPathFileUrl(fileName).substring(1);
        Path path = Paths.get(classPathFileUrl);

        if (Files.notExists(path)) {
            Files.createFile(path);
        }
        return path;
    }
}
